﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using NLog;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace JiveMessenger.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class ViewModelAddEmoticon : ViewModelBase
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private const int MaxEmoticonHeigth = 100;
        private const int MaxEmoticonWidth = 250;
        private IClient _currentClient;
        private bool _tooBigPixelSize;
        public RelayCommand BrowseForImageCommand { get; private set; }

        public string OriginalShortCut;

        private string _emoticonPath;
        public string EmoticonPath
        {
            get { return _emoticonPath; }
            set
            {
                if (_emoticonPath != value)
                {
                    _emoticonPath = value;
                    RaisePropertyChanged("EmoticonPath");
                    RaisePropertyChanged("IsShortcutTextBoxEnabled");
                }
            }
        }

        private string _imageErrorText;
        public string ImageErrorText
        {
            get { return _imageErrorText; }
            set
            {
                if (_imageErrorText != value)
                {
                    _imageErrorText = value;
                    RaisePropertyChanged("ImageErrorText");
                }
            }
        }

        private string _emoticonShortcut;
        public string EmoticonShortcut
        {
            get { return _emoticonShortcut; }
            set
            {
                if (_emoticonShortcut != value)
                {
                    _emoticonShortcut = value;
                    RaisePropertyChanged("EmoticonShortcut");
                }
            }
        }

        public bool IsShortcutTextBoxEnabled
        {
            get
            {
                return !string.IsNullOrEmpty(EmoticonPath);
            }
        }
        private string _shortcutErrorText;
        public string ShortcutErrorText
        {
            get { return _shortcutErrorText; }
            set
            {
                if (_shortcutErrorText != value)
                {
                    _shortcutErrorText = value;
                    RaisePropertyChanged("ShortcutErrorText");
                }
            }
        }


        private bool _isOkButtonEnabled;
        public bool IsOkButtonEnabled
        {
            get { return _isOkButtonEnabled; }
            set
            {
                if (_isOkButtonEnabled != value)
                {
                    _isOkButtonEnabled = value;
                    RaisePropertyChanged("IsOkButtonEnabled");
                }
            }
        }

        private byte[] _emoticonImageSource;
        public byte[] EmoticonImageSource
        {
            get { return _emoticonImageSource; }
            set
            {
                if (_emoticonImageSource != value)
                {
                    _emoticonImageSource = value;
                    RaisePropertyChanged("EmoticonImageSource");
                }
            }
        }
        ~ViewModelAddEmoticon()
        {
            Logger.Debug("ViewModelAddEmoticon destructed");
        }

        /// <summary>
        /// Initializes a new instance of the ViewModelAddEmoticon class.
        /// </summary>
        public ViewModelAddEmoticon(IClient currentClient)
        {
            _currentClient = currentClient;
            BrowseForImageCommand = new RelayCommand(BrowseForImageCommandAction);
            PropertyChanged += ViewModelAddEmoticon_PropertyChanged;
        }

        public override void Cleanup()
        {

            SimpleIoc.Default.Unregister<ViewModelAddEmoticon>(VmHelper.Locator.ViewModelAddEmoticonKey);
            VmHelper.Locator.ViewModelAddEmoticonKey = System.Guid.NewGuid().ToString();
            PropertyChanged -= ViewModelAddEmoticon_PropertyChanged;
            base.Cleanup();
        }

        void ViewModelAddEmoticon_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "EmoticonShortcut":
                    ValidateShortcut();
                    break;
            }
        }

        private void ValidateShortcut()
        {
            string error;
            if (!this._currentClient.ValidateEmoticonShortcut(this.EmoticonShortcut, this.OriginalShortCut, out error))
            {
                this.ShortcutErrorText = error;
                this.IsOkButtonEnabled = false;
            }
            else if (!String.IsNullOrEmpty(this.EmoticonShortcut) && !this._tooBigPixelSize)
            {
                this.ShortcutErrorText = "";
                this.IsOkButtonEnabled = true;
            }
            else
                this.IsOkButtonEnabled = false;
        }

        private void BrowseForImageCommandAction()
        {
            Messenger.Default.Send<NotificationMessageAction<string>>(new NotificationMessageAction<string>(this, "BrowseForImage", msg =>
                {
                    if (msg == null)
                        return;
                    EmoticonPath = msg;
                    bool isGif = EmoticonPath.IndexOf(".gif", StringComparison.OrdinalIgnoreCase) !=-1;


                    int sizeInKB = isGif?150:50;
                    bool tooBigFileSize = new FileInfo(msg).Length > 1024 * sizeInKB;
                    _tooBigPixelSize = CheckImageSize(EmoticonPath);

                    if (tooBigFileSize)
                    {

                        this.ImageErrorText = string.Format("Max file size is {0}","50KB","150KB (gif)");
                        this.IsOkButtonEnabled = false;
                        this.EmoticonPath = "";
                    }
                    else if (_tooBigPixelSize)
                    {

                        this.ImageErrorText = string.Format("Image is larger than {0}x{1} px.", MaxEmoticonWidth, MaxEmoticonHeigth);
                        this.IsOkButtonEnabled = false;
                        this.EmoticonPath = "";
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(EmoticonShortcut))
                            this.IsOkButtonEnabled = true;
                        this.ImageErrorText = "";
                    }
                    if (!string.IsNullOrEmpty(EmoticonPath))
                        SetImage(EmoticonPath);
                    Messenger.Default.Send(new NotificationMessage(this, "FocusShortcutTextbox"));
                }));


        }
        public void SetImage(string source)
        {
            this.EmoticonImageSource = StaticMethods.LoadImageData(source);// StaticMethods.BitmapFromUri(new Uri(source));
        }
        private bool CheckImageSize(string fileName)
        {

            byte[] imageBytes = StaticMethods.LoadImageData(fileName);


            bool tooBig = false;

            // the following will decode the image to its natural size

            BitmapSource imageSource = StaticMethods.ByteArrayToBitmap(imageBytes);



            if (Math.Round(imageSource.Width) > MaxEmoticonWidth)
            {
                tooBig = true;
            }

            if (Math.Round(imageSource.Height) > MaxEmoticonHeigth)
            {
                tooBig = true;
            }
           
            return tooBig;
        }
    }
}